package com.apk.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java_util.coo_util.C_File;
import java_util.coo_util.Log.C_Log;
import java_util.coo_util.Log.C_LogTxtSave;
import java_util.uitl.C_ImageUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class C_Ipa2Sign {
    static final String Payload = "Payload";

    public static void S_build(String _build, String xcodeTemplatePath, int index, String rootPath, File wordDir, String buildId) throws Exception {
        String wordPath = wordDir.getPath() + "/";
        String dirName = wordDir.getName();
        C_File.S_CareteDir(rootPath + _build);

        C_Log.Log("build.开始__________" + dirName);


        build_config setting = new build_config();
        if (!setting.S_LoadData(wordPath)) {
            return;
        }
        setting.S_SetInfo(wordDir, buildId, 3);
        C_cmd.S_GotoPath(rootPath);

        String unzipRootPath = S_unfoldIpa(setting, _build, rootPath, wordPath);
        C_IpaUtil.S_fileCopy(C_IpaUtil.embedded + ".txt", unzipRootPath + C_IpaUtil.embedded);
//        String plist0Path = rootPath + _build + "embedded.mobileprovision";
//        C_File.S_fileCopy(unzipRootPath + "/embedded.mobileprovision", plist0Path);
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_fixData);
        S_FixPlist(unzipRootPath, setting);
        S_copyAssets(unzipRootPath, wordPath);
        S_copyIcon(unzipRootPath, wordPath, rootPath, xcodeTemplatePath, setting);
        S_FixConfig(unzipRootPath, setting);

        S_ipa2build3(setting, _build, rootPath, dirName);
        Thread.sleep(200);

        // C_cmd.S_Runtime("rm -rf " + plist0Path);
        //JOptionPane.showMessageDialog(null, setting.o_gameName + "--打包完成了", "好消息", JOptionPane.PLAIN_MESSAGE);
        C_LogTxtSave.S_SaveData();
    }

    static String S_unfoldIpa(build_config setting, String _build, String rootPath, String wordPath) throws Exception {
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_unzip);
        String appUnfoldPath0 = rootPath + _build + Payload;
        //C_Log.Log("--------------删除________" + appUnfoldPath0);

        C_cmd.S_delete(appUnfoldPath0);
        //C_Log.Log("--------------解压.ipa.________" + _build + " app.ipa");
        if ("".equals(_build)) {
            C_cmd.S_Runtime("unzip  app.ipa");
        } else {
            String appPath = build_config.S_SearchFilePath(rootPath ,"app.ipa");
            C_cmd.S_Runtime("unzip -d  " + rootPath + _build + "  " + appPath);
        }

        //C_Log.Log("-------------解压.ipa..结束.________" + _build);
        return S_getUnzipRootPath(appUnfoldPath0);
    }


    public static String S_getUnzipRootPath(String patha) {
        C_Log.Log("--------------S_getUnzipRootPath.________");
        String path = patha;
        File file = new File(path);
        File[] tempList = file.listFiles();
        C_Log.Log("该目录下对象个数：....." + tempList.length);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isDirectory()) {
                return tempList[i].getPath();
            }
        }
        return null;
    }

    static void S_FixPlist(String unzipRootPath, build_config setting) throws Exception {
        String fileName = unzipRootPath + "/Info.plist";
        C_Log.Log("----修改plist文件________" + fileName);
        C_cmd.S_Runtime("plutil -convert json " + fileName);


        String sss = C_File.ReadAllTxt(fileName);
        JSONObject jobj = JSON.parseObject(sss);
        if (setting.o_gameName == null) {
            setting.o_gameName = (String) jobj.get(CFBundleDisplayName);
        } else {
            jobj.put(CFBundleDisplayName, setting.o_gameName);
        }
        setting.o_lastPackageName = (String) jobj.get(CFBundleIdentifier);
        if (setting.o_packageName.length() > 2) {
            jobj.put(CFBundleIdentifier, setting.o_packageName);
        } else {
            setting.o_packageName = setting.o_lastPackageName;
        }
        C_Log.LogWarningFormat("获取游戏信息.......%s........%s.......%s", setting.o_packageName, setting.o_packageName, setting.o_lastPackageName);
        C_File.S_Save(fileName, jobj.toString());

        C_cmd.S_Runtime("plutil -convert binary1 " + fileName);

        C_Log.Log("----修改plist文件__完成______" + fileName);
    }

    static final String CFBundleDisplayName = "CFBundleDisplayName";
    static final String CFBundleIdentifier = "CFBundleIdentifier";


    static void S_copyAssets(String unzipRootPath, String wordPath) {
        C_Log.Log("S_copyAssets...." + unzipRootPath);
        String sourecDir = wordPath + "assets/";
        String targetDir = unzipRootPath + "/Data/Raw/";
        File sourec = new File(sourecDir);
        if (!sourec.exists()) {
            sourec.mkdirs(); //创建目录
            C_Log.LogError("目录==null...无法拷贝...." + sourecDir);
        } else {
            C_File.S_copyDir(sourecDir, targetDir);
        }
    }

    static void S_copyIcon(String unzipRootPath, String wordPath, String rootPath, String xcodeTemplatePath, build_config setting) throws Exception {
        C_Log.Log("build.S_copyIcon..开始.________" + unzipRootPath);
        String sourcePath = wordPath + "icon.png";
        File file = new File(sourcePath);
        if (!file.exists()) {
            C_Log.LogWarningFormat("源icon不存在....无法替换........." + sourcePath);
            return;
        }
        for (C_image icon0 : iconPaths) {
            String targetPath = null;
            if (icon0.type == 1) {
                targetPath = unzipRootPath + "/" + icon0.name;
            } else if (icon0.type == 2) {
                targetPath = xcodeTemplatePath + patt + icon0.name;
            } else {
                targetPath = "";
            }
            C_ImageUtil.S_resizePng(sourcePath, targetPath, icon0.size, icon0.size, false);
        }
        C_IpaUtil.S_buildXcodeTemplate(rootPath, unzipRootPath, setting);
        C_Log.Log("build.S_copyIcon..结束._______" + unzipRootPath);
    }

    final static String patt = "/xcodeTemplate/Assets.xcassets/AppIcon.appiconset/";

    static C_image[] iconPaths = new C_image[]{
            new C_image(1, "AppIcon20x20@2x.png", 20),
            new C_image(1, "AppIcon20x20@2x~ipad.png", 20),
            new C_image(1, "AppIcon20x20@3x.png", 20),
            new C_image(1, "AppIcon20x20~ipad.png", 20),
            new C_image(1, "AppIcon29x29.png", 29),
            new C_image(1, "AppIcon29x29@2x.png", 29),
            new C_image(1, "AppIcon29x29@2x~ipad.png", 29),
            new C_image(1, "AppIcon29x29@3x.png", 29),
            new C_image(1, "AppIcon29x29~ipad.png", 29),
            new C_image(1, "AppIcon40x40@2x.png", 40),
            new C_image(1, "AppIcon40x40@2x~ipad.png", 40),
            new C_image(1, "AppIcon40x40@3x.png", 40),
            new C_image(1, "AppIcon40x40~ipad.png", 40),
            new C_image(1, "AppIcon60x60@2x.png", 60),
            new C_image(1, "AppIcon60x60@3x.png", 60),
            new C_image(1, "AppIcon76x76@2x~ipad.png", 76),
            new C_image(1, "AppIcon76x76~ipad.png", 76),
            new C_image(1, "AppIcon83.5x83.5@2x~ipad.png", 76),
            new C_image(2, "Icon-iPad-76.png", 76),
            new C_image(2, "Icon-iPad-152.png", 152),
            new C_image(2, "Icon-iPad-167.png", 168),
            new C_image(2, "Icon-iPad-Notification-20.png", 20),
            new C_image(2, "Icon-iPad-Notification-40.png", 40),
            new C_image(2, "Icon-iPad-Settings-29.png", 29),
            new C_image(2, "Icon-iPad-Settings-58.png", 58),
            new C_image(2, "Icon-iPad-Spotlight-40.png", 40),
            new C_image(2, "Icon-iPad-Spotlight-80.png", 80),
            new C_image(2, "Icon-iPhone-120.png", 120),
            new C_image(2, "Icon-iPhone-180.png", 180),
            new C_image(2, "Icon-iPhone-Notification-40.png", 40),
            new C_image(2, "Icon-iPhone-Notification-60.png", 60),
            new C_image(2, "Icon-iPhone-Settings-29.png", 29),
            new C_image(2, "Icon-iPhone-Settings-58.png", 58),
            new C_image(2, "Icon-iPhone-Settings-87.png", 87),
            new C_image(2, "Icon-iPhone-Spotlight-80.png", 80),
            new C_image(2, "Icon-iPhone-Spotlight-120.png", 120),
            new C_image(2, "Icon-Store-1024.png", 1024),

    };

    //配置icon路径信息
    static class C_image {
        public int type;
        public String name;
        public int size;

        public C_image(int type, String name, int size) {
            this.type = type;
            this.name = name;
            this.size = size;
        }
    }


    static void S_FixConfig(String unzipRootPath, build_config setting) throws IOException {
        String path = unzipRootPath + "/Data/Raw/config.txt";
        build_config.S_FixConfig(path, setting);
    }

    static void S_ipa2build3(build_config setting, String _build, String rootPath, String dirName) throws Exception {
        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_app2build);
        String genPath = dirName + ".ipa";
        String ipaPath = rootPath + _build + dirName + ".ipa";
        C_cmd.S_delete(ipaPath);

        C_Log.Log("--------build.S_apk2build..开始.________" + genPath);


        String cdData = "cd " + rootPath + _build + "\t\n";
        cdData += "zip -r " + genPath + " " + Payload + "\t\n";
        cdData += "fastlane sigh resign " + genPath + " --signing_identity \"iPhone Distribution: yangyang li (V7CL5M7BN8)\" -p \"embedded.mobileprovision\" \t\n";
        cdData += "cd  " + rootPath;

        String buildFilePath = rootPath + "temp_2build.sh";
        C_File.S_Save(buildFilePath, cdData);

        C_ProgressReport.S_SendProgress(setting, C_ProgressReport.o_app2Sign);
        C_cmd.S_Runtime("chmod 777 " + buildFilePath);
        //C_cmd.S_Runtime("source ./cd.sh");
        C_cmd.S_Runtime("" + buildFilePath);


        C_cmd.S_delete(buildFilePath);
        C_Log.Log("--------------build.S_apk2build..结束.______" + genPath);
        C_ProgressReport.S_upload(setting, ipaPath);
    }
}
